import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

export const useAuthStore = defineStore('auth', () => {
  const router = useRouter()
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
  const isAuthenticated = ref(!!token.value)

  // 登录方法
  const login = async (username, password) => {
    try {
      // 这里模拟API调用，实际项目中需要替换为真实的API请求
      if (username === 'admin' && password === 'admin') {
        const mockToken = 'mock_token_' + Date.now()
        const mockUser = {
          id: 1,
          username: username,
          name: '管理员'
        }

        // 保存认证信息
        token.value = mockToken
        user.value = mockUser
        isAuthenticated.value = true
        
        // 存储到本地存储
        localStorage.setItem('token', mockToken)
        localStorage.setItem('user', JSON.stringify(mockUser))

        return true
      } else {
        throw new Error('用户名或密码错误')
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  // 退出登录
  const logout = () => {
    // 清除认证信息
    token.value = ''
    user.value = null
    isAuthenticated.value = false
    
    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    
    // 跳转到登录页
    router.push('/login')
  }

  // 检查认证状态
  const checkAuth = () => {
    const storedToken = localStorage.getItem('token')
    if (storedToken) {
      token.value = storedToken
      user.value = JSON.parse(localStorage.getItem('user'))
      isAuthenticated.value = true
    } else {
      isAuthenticated.value = false
    }
  }

  return {
    token,
    user,
    isAuthenticated,
    login,
    logout,
    checkAuth
  }
}) 